// 引入 router 在vuex内使用router跳转
import router from '@/router'

import { ElMessage, ElNotification } from '@/assets/js/message.js'
import http from '@/assets/js/requset'

let tokenKey = 'token'
let tokenStr = window.sessionStorage.getItem(tokenKey)
let tokenVal = {}
if (tokenStr) {
    tokenVal = JSON.parse(tokenStr)
}

const app = {
    // 如果为true---->调用方法需添加命名空间 如tabviews/createTab
    namespaced: true,
    state: {
        tokenHeader:tokenVal.tokenHeader || "",
        isLog: tokenVal.isLog || false,
        logDate: tokenVal.logDate || null,
        userName: tokenVal.userName,
        roleIds: tokenVal.roleIds,
        userId : tokenVal.userId,
        roleCodes: tokenVal.roleCodes,
        token: tokenVal.token,
        // estateId: tokenVal.estateId,
        // estateName: tokenVal.estateName,
    },

    // dispatch 触发--->actions 异步变更
    actions: {
        //   登录记录验证
        logAction({ commit }, data) {
            if (data) {
                commit('LOG_ACTION', data)
            }
        },
        logCancel({ commit, dispatch }) {
            commit('LOG_CANCEL')
        },
    },
    // 外部方法 commit触发--->mutaions  同步变更
    mutations: {
        LOG_ACTION(state, data) {
            state.isLog = true
            state.logDate = new Date()
            state.userId = data.UserId
            state.userName = data.UserName
            state.token = data.Token
            state.roleIds = data.RoleIds;
            state.roleCodes = data.RoleCodes;
            state.tokenHeader=data.tokenHeader || ""
            // state.estateId= tokenVal.estateId,
            // state.estateName = data.estateName

            let val = {
                isLog: state.isLog,
                userId : state.userId,
                logDate: state.logDate,
                userName: state.userName,
                token: state.token,
                roleIds: state.roleIds,
                roleCodes: state.roleCodes,
                tokenHeader: state.tokenHeader,
                // estateId: state.estateId,
                // estateName: state.estateName
            }
            window.sessionStorage.setItem(tokenKey, JSON.stringify(val))

            // //推荐的方式
            // setTimeout(function () {
            //     router.push('/')
            // }, 1000);

        },
        LOG_CANCEL(state) {
            state.isLog = null
            state.logDate = null

            window.sessionStorage.removeItem(tokenKey)
            this.dispatch('tabs/setTabs', { clear: true })
            this.dispatch('navMenus/removeMenus', {}, {})
            router.push('/login')
        }
    }
}

export default app